using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;

namespace BlockOS.Client
{
    public class OnScreenClick : OnScreenControl, IPointerDownHandler, IPointerUpHandler
    {
        [SerializeField]
        private float m_MaxTime;

        [InputControl(layout = "Button")]
        [SerializeField]
        private string m_ControlPath;
        protected override string controlPathInternal { get => m_ControlPath; set => m_ControlPath = value; }

        private bool m_IsPointerDown;
        private float m_Timer = 0;

        private void Update()
        {
            if (m_IsPointerDown)
            {
                m_Timer += Time.deltaTime;
            }
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            m_IsPointerDown = true;
            m_Timer = 0;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            m_IsPointerDown = false;
            if (m_MaxTime < 0 || m_Timer < m_MaxTime)
            {
                SendValueToControl(1.0f);
                StartCoroutine(CoDelayFrames(3, () => SendValueToControl(0.0f)));
            }
        }

        private IEnumerator CoDelayFrames(int frames, Action action)
        {
            while (frames-- > 0)
            {
                yield return null;
            }
            action();
        }
    }
}
